package meiyunting.shiwuzhaoling.controller;

import meiyunting.shiwuzhaoling.dto.ItemDTO;
import meiyunting.shiwuzhaoling.model.Item;
import meiyunting.shiwuzhaoling.model.ItemStatus;
import meiyunting.shiwuzhaoling.model.ItemType;
import meiyunting.shiwuzhaoling.model.User;
import meiyunting.shiwuzhaoling.service.ItemService;
import meiyunting.shiwuzhaoling.service.UserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 失物招领信息控制器
 */
@Controller
@RequestMapping("/items")
public class ItemController {

    private static final Logger logger = LoggerFactory.getLogger(ItemController.class);
    private final ItemService itemService;
    private final UserService userService;

    public ItemController(ItemService itemService, UserService userService) {
        this.itemService = itemService;
        this.userService = userService;
    }

    /**
     * 首页 - 列表页
     */
    @GetMapping
    public String listItems(
            @RequestParam(required = false) ItemStatus status,
            @RequestParam(required = false) ItemType type,
            @RequestParam(required = false) String keyword,
            Model model) {
        
        List<Item> items;
        
        if (status != null && type != null) {
            items = itemService.getItemsByStatusAndType(status, type);
        } else if (status != null) {
            items = itemService.getItemsByStatus(status);
        } else if (type != null) {
            items = itemService.getItemsByType(type);
        } else if (keyword != null && !keyword.isEmpty()) {
            items = itemService.searchItems(keyword);
        } else {
            items = itemService.getAllItems();
        }
        
        model.addAttribute("items", items);
        model.addAttribute("itemTypes", ItemType.values());
        model.addAttribute("itemStatuses", ItemStatus.values());
        model.addAttribute("selectedStatus", status);
        model.addAttribute("selectedType", type);
        model.addAttribute("keyword", keyword);
        
        // 添加当前用户信息
        User currentUser = userService.getCurrentUser();
        model.addAttribute("currentUser", currentUser);
        
        return "item/list";
    }

    /**
     * 显示新增表单
     */
    @GetMapping("/new")
    @PreAuthorize("isAuthenticated()")
    public String showNewItemForm(Model model) {
        model.addAttribute("item", new ItemDTO());
        model.addAttribute("itemTypes", ItemType.values());
        model.addAttribute("itemStatuses", ItemStatus.values());
        return "item/form";
    }

    /**
     * 处理表单提交
     */
    @PostMapping
    @PreAuthorize("isAuthenticated()")
    public String createItem(
            @ModelAttribute ItemDTO itemDTO,
            @RequestParam(value = "image", required = false) MultipartFile image,
            RedirectAttributes redirectAttributes) {
        
        User currentUser = userService.getCurrentUser();
        
        logger.info("提交新物品信息: status={}, type={}, title={}, lostTime={}", 
                itemDTO.getStatus(), itemDTO.getType(), itemDTO.getTitle(), itemDTO.getLostTime());
        
        Item createdItem = itemService.createItem(itemDTO, image, currentUser);
        logger.info("已创建物品信息: id={}, lostTime={}", createdItem.getId(), createdItem.getLostTime());
        
        redirectAttributes.addFlashAttribute("successMessage", "信息发布成功！");
        return "redirect:/items";
    }

    /**
     * 显示详情页
     */
    @GetMapping("/{id}")
    public String showItemDetail(@PathVariable Long id, Model model) {
        Optional<Item> optionalItem = itemService.getItemById(id);
        if (optionalItem.isPresent()) {
            Item item = optionalItem.get();
            model.addAttribute("item", item);
            
            // 添加当前用户信息
            User currentUser = userService.getCurrentUser();
            model.addAttribute("currentUser", currentUser);
            model.addAttribute("canClaim", currentUser != null && item.getClaimedBy() == null);
            
            // 获取所有用户，用于选择认领者
            List<User> allUsers = userService.findAllUsers();
            model.addAttribute("allUsers", allUsers);
            
            return "item/detail";
        } else {
            return "redirect:/items";
        }
    }

    /**
     * 显示编辑表单
     */
    @GetMapping("/{id}/edit")
    @PreAuthorize("isAuthenticated()")
    public String showEditForm(@PathVariable Long id, Model model) {
        Optional<Item> optionalItem = itemService.getItemById(id);
        if (optionalItem.isPresent()) {
            Item item = optionalItem.get();
            
            // 验证是否是物品的发布者
            User currentUser = userService.getCurrentUser();
            if (!item.getUser().getId().equals(currentUser.getId())) {
                return "redirect:/items";
            }
            
            ItemDTO itemDTO = new ItemDTO(
                    item.getStatus(),
                    item.getType(),
                    item.getTitle(),
                    item.getDescription(),
                    item.getContactInfo(),
                    item.getLostTime()
            );
            
            model.addAttribute("item", itemDTO);
            model.addAttribute("itemId", id);
            model.addAttribute("itemTypes", ItemType.values());
            model.addAttribute("itemStatuses", ItemStatus.values());
            model.addAttribute("existingImagePath", item.getImagePath());
            
            return "item/form";
        } else {
            return "redirect:/items";
        }
    }

    /**
     * 处理编辑表单提交
     */
    @PostMapping("/{id}")
    @PreAuthorize("isAuthenticated()")
    public String updateItem(
            @PathVariable Long id,
            @ModelAttribute ItemDTO itemDTO,
            @RequestParam(value = "image", required = false) MultipartFile image,
            RedirectAttributes redirectAttributes) {
        
        User currentUser = userService.getCurrentUser();
        
        logger.info("更新物品信息: id={}, status={}, type={}, title={}, lostTime={}", 
                id, itemDTO.getStatus(), itemDTO.getType(), itemDTO.getTitle(), itemDTO.getLostTime());
        
        try {
            Item updatedItem = itemService.updateItem(id, itemDTO, image, currentUser);
            logger.info("已更新物品信息: id={}, lostTime={}", updatedItem.getId(), updatedItem.getLostTime());
            
            redirectAttributes.addFlashAttribute("successMessage", "信息更新成功！");
        } catch (RuntimeException e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
        }
        
        return "redirect:/items";
    }

    /**
     * 删除信息
     */
    @PostMapping("/{id}/delete")
    @PreAuthorize("isAuthenticated()")
    public String deleteItem(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            User currentUser = userService.getCurrentUser();
            itemService.deleteItem(id, currentUser);
            redirectAttributes.addFlashAttribute("successMessage", "信息已删除！");
        } catch (RuntimeException e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
        }
        return "redirect:/items";
    }

    /**
     * 认领物品
     */
    @PostMapping("/{id}/claim")
    @PreAuthorize("isAuthenticated()")
    public String claimItem(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            User currentUser = userService.getCurrentUser();
            itemService.claimItem(id, currentUser);
            redirectAttributes.addFlashAttribute("successMessage", "物品认领成功！");
        } catch (RuntimeException e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
        }
        return "redirect:/items/" + id;
    }

    /**
     * 我的物品列表
     */
    @GetMapping("/my")
    @PreAuthorize("isAuthenticated()")
    public String listMyItems(Model model) {
        User currentUser = userService.getCurrentUser();
        List<Item> items = itemService.getItemsByUser(currentUser);
        
        model.addAttribute("items", items);
        model.addAttribute("itemTypes", ItemType.values());
        model.addAttribute("itemStatuses", ItemStatus.values());
        model.addAttribute("currentUser", currentUser);
        
        return "item/my-items";
    }
} 